package com.wf.mock.app.mina.app.processor.impl;

import java.util.concurrent.TimeUnit;

import lombok.extern.log4j.Log4j;

import org.apache.mina.core.session.IoSession;

import com.alibaba.fastjson.JSONObject;
import com.wf.mock.app.mina.MessageIntentType;
import com.wf.mock.app.mina.RetrySendMsgManager;
import com.wf.mock.app.mina.app.processor.IMessageProcessor;
import com.wf.mock.app.mina.dto.NormalCloudMsgDTO;
import com.wf.mock.app.mina.dto.RawMessageDTO;
import com.wf.mock.app.utils.MinaUtils;

@Log4j
public class Portal2APPMessageProcessorImpl implements IMessageProcessor {

	public void process(RawMessageDTO msgDto, IoSession session) {

		JSONObject msgBody = msgDto.getMsgBody();

		String markId = msgBody.getString("markId");
		String userId = msgBody.getString("userId");
		RetrySendMsgManager.INSTANCE.removeEvent(markId, userId);

		long sendtime;
		try {
			Object object = msgBody.getString("content").split("@@")[1];
			sendtime = Long.valueOf(object.toString());
		} catch (Exception e) {
			sendtime = System.currentTimeMillis();
		}

		log.info("--------cost time -------" + (System.currentTimeMillis() - sendtime) + "ms");
		log.info(msgDto);
		session.write(MessageIntentType.APPCONFIRM.getPreffix() + "{'markId':'" + msgBody.getString("markId")
				+ "','state':'SUCCESS'}");

		sendReadMsg(session, msgDto);

	}

	private static void sendReadMsg(IoSession session, RawMessageDTO msgDto) {

		JSONObject body = msgDto.getMsgBody();

		Integer type = body.getInteger("cloudMsgType");

		if (type != null && type.intValue() == 0) {
			NormalCloudMsgDTO dto = JSONObject.toJavaObject(body, NormalCloudMsgDTO.class);
			if (!dto.getUserId().equals(dto.getSenderId())) {

				String uuid = MinaUtils.generateUUID();
				String msg = MessageIntentType.APP2PORTAL + "{'userId':'" + dto.getUserId()
						+ "','domain':'wafertest.com','operateType':'READMSG','markId':'" + uuid
						+ "','unreadSize':0,'msgId':" + dto.getMsgId() + ",'sessionId':" + dto.getSessionId()
						+ ",'extMsgId':" + JSONObject.parseObject(dto.getExt()).getIntValue("id") + ",'msgType':"
						+ dto.getMsgType() + "}";
				log.info("send read msg:" + msg);
				try {
					TimeUnit.MILLISECONDS.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				session.write(msg);
			}

		}

	}

}
